// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// F [author] rhyme_lph
// o [email]  rhymelph@gmail.com
// t [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/payslips_entity.dart';
import 'package:finance_app/src/entities/payslips_item_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/chart/normal_bar_one_way_chart.dart';
import 'package:finance_app/src/widgets/common/expandable.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/payslips_item.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/hr_payroll/views/payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class PayrollView extends StatefulWidget {
  @override
  _PayrollViewState createState() => _PayrollViewState();
}

class _PayrollViewState extends State<PayrollView>
    with
        StatefulPresenter<PayrollView, HrAndPayrollProvider, PayrollProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: SmartRefresher(
          controller: provider.refreshController,
          onRefresh: provider.onRefresh,
          onLoading: provider.onLoadMore,
          enablePullUp: false,
          child: ListView(
            controller: provider.controller,
            children: [
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                AppSpaces.h20,
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                ListHeaderItem(
                  title: S.current.salary_overview,
                ),
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                AppSpaces.h20,
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                listBuilder<PayslipsEntity>(
                  selector: (_, __) => __.data,
                  builder: (BuildContext context, value, Widget child) =>
                      NormalBarOneWayChart(
                    payslips: provider.data,
                  ),
                ),
              AppSpaces.h25,
              listBuilder<int>(
                selector: (_, __) => __.payslipsList?.length,
                builder: (BuildContext context, int value, Widget child) =>
                    Column(
                  children: provider.payslipsMap.entries.map((e) {
                    e.value.data
                        .sort((a, b) => b.startDate.compareTo(a.startDate));
                    Map<String, List<PayslipsItemEntity>> map = {};

                    for (final item in e.value.data) {
                      DateTime start = DateTimeUtils.toDateTime(
                          item.startDate, 'yyyy-MM-dd');
                      String month = DateTimeUtils.formatDateTime(start, "MMM");
                      if (map.containsKey(month)) {
                        map[month].add(item);
                      } else {
                        map[month] = [item];
                      }
                    }
                    List<Widget> children = [];
                    for (final item in map.entries) {
                      children.add(TransactionRecordTitleItem(
                        topPadding: getDp(14),
                        title: item.key,
                      ));
                      children.add(AppSpaces.grayH05);
                      children
                          .addAll(item.value.map(buildPayslipWidget).toList());
                    }
                    return ListExpandableItem(
                      controller: e.value.controller,
                      titleSpans: [
                        TextSpan(text: provider.getGroupName(e.key)),
                        if (e.key == 'open')
                          TextSpan(
                              text: '(${e.value.data.length})',
                              style: TextStyle(
                                color: aceRedColor,
                              ))
                      ],
                      content: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: children,
                      ),
                    );
                  }).toList(),
                ),
              ),
              if (Config.hasPermission(PermissionUtils.hrPayroll))
                ListExpandableItem(
                  controller: ExpandableController(initialExpanded: true),
                  titleSpans: [
                    TextSpan(text: S.current.cpf_contribution),
                  ],
                  content: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: buildCpfList(),
                  ),
                ),
              AppSpaces.h50,
            ],
          ),
        ),
      );

  Widget buildPayslipWidget(PayslipsItemEntity e) {
    return PressedOpacityButton(
      onPressed: () => provider.onNavPayslipDetail(e),
      child: PayslipsItem(
        name: e.name,
        timeRange:
            '${DateTimeUtils.formatDateTimeString(e.startDate)} - ${DateTimeUtils.formatDateTimeString(e.endDate)}',
        currency: e.incomeData?.first?.currencyCode,
        amount: (e.nettAmount + e.reimbursement).toDouble(),
        errorMessage: e.errorMessage,
        status: e.status,
      ),
    );
  }

  List<Widget> buildCpfList() {
    List<Widget> widgets = [];
    provider.cpfsList.forEach((cpf) {
      widgets.add(PressedOpacityButton(
        onPressed: () => provider.onNavCPFDetail(cpf),
        child: NormalFormWrapper(
          leftPadding: getDp(32),
          rightPadding: getDp(32),
          topPadding: getDp(24),
          bottomPadding: getDp(23),
          hasBottomBorder: true,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    constraints: BoxConstraints(minWidth: 80),
                    child: Text(
                      '${cpf.month} ${cpf.year}',
                      style: TextStyle(
                        color: aceBlackColor,
                        fontSize: getSp(18),
                        fontWeight: FontWeight.w700,
                        height: 14 / 18,
                      ),
                    ),
                  ),
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  if (cpf.status == "open")
                    RedTagWidget(
                      content: S.current.unpaid,
                    ),
                  if (cpf.status == "closed")
                    GreenTagWidget(
                      content: S.current.paid,
                    ),
                  AppSpaces.h10,
                  Text(
                    'SGD ${cpf.total.toStringAsFixed(2)}',
                    style: TextStyle(
                      color: aceBlackColor,
                      fontSize: getSp(16),
                      fontWeight: FontWeight.w700,
                      height: 14 / 18,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ));
    });
    return widgets;
  }
}
